package cn.tedu._05mvcboot03.controller;

import cn.tedu._05mvcboot03.common.response.JsonResult;
import cn.tedu._05mvcboot03.common.response.StatusCode;
import cn.tedu._05mvcboot03.mapper.UserMapper;
import cn.tedu._05mvcboot03.pojo.dto.UserArticleDTO;
import cn.tedu._05mvcboot03.pojo.dto.UserLoginDTO;
import cn.tedu._05mvcboot03.pojo.entity.Article;
import cn.tedu._05mvcboot03.pojo.vo.AirticleVO;
import cn.tedu._05mvcboot03.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import jdk.nashorn.internal.ir.annotations.Ignore;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

@Slf4j
@RestController
@Validated
@Api(tags = "用户模块")
@RequestMapping("/v1/users/")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @ApiOperation("登录功能")
    @PostMapping("login")
    public JsonResult login(@RequestBody UserLoginDTO userLoginDTO,@ApiIgnore HttpSession session){
        UserVO userVO = userMapper.selectUser(userLoginDTO.getUsername(), userLoginDTO.getPassword());
        log.debug("userLoginDTO = "+userLoginDTO);
        if (userLoginDTO.getUsername().equals(userVO.getUsername()) && userLoginDTO.getPassword().equals(userVO.getPassword())){
            session.setAttribute("user",userVO);
            return JsonResult.ok();
        }else {
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
    }
    @ApiOperation("发布文章")
    @PostMapping("article")
    public JsonResult article(@RequestBody @Validated UserArticleDTO userArticleDTO,@ApiIgnore HttpSession session){
        UserVO userVO = (UserVO) session.getAttribute("user");
//        if (userVO==null){
//            return new JsonResult(StatusCode.NOT_LOGIN);
//        }
        Article article = new Article();
        BeanUtils.copyProperties(userArticleDTO,article);
        article.setUser_id(userVO.getId());
        int d= userMapper.insert(article);
        if (d>0){
            return JsonResult.ok();
        }else {
            return new JsonResult(StatusCode.VALIDATED_ERROR);
        }
    }
    @ApiOperation("查询指定文章")
    @GetMapping("selectByArticleId")
    @ApiImplicitParam(name = "id",value = "用户ID",required = true,dataType = "Long")
    public JsonResult selectByArticleId(@Range(min = 1,max = 100,message = "文章id为1到100") @RequestParam Long id){
        log.debug("id="+id);
        AirticleVO airticleVO = userMapper.selectByArticleId(id);
        return JsonResult.ok(airticleVO);
    }

}
